package com.zhenyi.boya.index;

import java.io.File;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.boya.common.model.ByCategory;
import com.boya.common.model.ByCertification;
import com.boya.common.model.ByExport;
import com.boya.common.model.ByImport;
import com.boya.common.model.ByLog;
import com.boya.common.model.ByMeal;
import com.boya.common.model.ByNutrition;
import com.boya.common.model.ByReport;
import com.boya.common.model.BySchool;
import com.boya.common.model.ByStock;
import com.boya.common.model.ByStockLog;
import com.boya.common.model.ByStorage;
import com.cenjiawen.common.IndexController;
import com.cjw.model.DBMap;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.utils.AESUtils;
import com.utils.AuthUtils;
import com.utils.DateUtils;
import com.utils.PathUtils;
import com.zhenyi.boya.interceptor.AuthInterceptor;
import com.zhenyi.boya.interceptor.InfoInterceptor;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

@Before({ AuthInterceptor.class, InfoInterceptor.class })
public class HomeController extends IndexController {

	private static final String AES_KEY = "boya!@#$%^&*()_+";

	private BySchool getSchool() {
		return BySchool.dao.findById(Long.valueOf(AuthUtils.getTokenUid(this)));
		// return BySchool.dao.findById(1);
	}

	private boolean log(String title, String content, String desc) {
		ByLog log = new ByLog();
		log.setTitle(title);
		log.setContent(content);
		log.setDesc(desc);
		log.setAddTime();
		log.setSchoolId(getSchool().getId());
		return log.save();
	}

	protected void setRainbow(Page<?> pages) {
		Integer requestPage = getParaToInt("page");

		HttpServletRequest request = getRequest();
		String url = request.getRequestURL().toString();
		String queryurl = request.getQueryString();
		if (StrKit.notBlank(queryurl)) {
			if (requestPage != null) {
				queryurl = queryurl.replace("&page=" + requestPage, "");
				queryurl = queryurl.replace("page=" + requestPage, "");
				if (StrKit.notBlank(queryurl)) {
					url = url + "?" + queryurl + "&page=";
				} else {
					url = url + "?page=";
				}
			} else {
				url = url + "?" + queryurl + "&page=";
			}
		} else {
			url = url + "?page=";
		}
		int pageTotal = pages.getTotalPage();
		int pageTotalRow = pages.getTotalRow();
		int page = pages.getPageNumber();
		int[] rainbow = PageUtil.rainbow(pages.getPageNumber(), pageTotal);
		setAttr("rainbow", rainbow);
		setAttr("pageUrl", url);
		setAttr("pageTotalRow", pageTotalRow);
		setAttr("pageSize", pages.getPageSize());
		setAttr("pageCurrent", page);
	}
	
	protected void setReferer() {
		setAttr("referer", getRequest().getHeader("Referer"));
	}

	@Clear
	public void login() {
		String account = getPara("account");
		String password = getPara("password");
		try {
			password = AESUtils.decrypt(AES_KEY, password);
			if (password == null) {
				renderFailure();
				return;
			}
		} catch (Exception e) {
			renderFailure();
			return;
		}
		if (!StrKit.notBlank(account, password)) {
			renderFailure(500, "账号/密码错误.");
			return;
		}
		DBMap maps = new DBMap();
		maps.put("account", account);
		maps.put("password", password);
		BySchool user = BySchool.dao.searchFirst(maps);
		if (user == null) {
			renderFailure(500, "账号/密码错误");
			return;
		}
		String token = AuthUtils.login(String.valueOf(user.getId()), this);
		renderSuccess(user);
	}

	public void logout() {
		AuthUtils.logout(this);
		render("/boya/login.html");
	}

	@Clear
	public void signIn() {
		render("/boya/login.html");
	}

	public void index() {
		// Long schoolId = getParaToLong("schoolId");

		Kv kv = Kv.create();
		String categoryString = getPara("categoryString");
		if (StrKit.notBlank(categoryString)) {
			kv.set("categoryString", categoryString);
			setAttr("categoryString", categoryString);
		}
		String name = getPara("name");
		if (StrKit.notBlank(name)) {
			kv.set("name", name);
			setAttr("name", name);
		}
		// kv.set("schoolId", schoolId);
		SqlPara sqlPara = Db.use("boya").getSqlPara("FindStorage", kv);
		Page<ByStorage> pages = ByStorage.dao.paginate(getPage(), PAGE_SIZE, sqlPara);
		setRainbow(pages);
		setAttr("list", pages.getList());
		render("/boya/storage.html");
	}

	public void addStorage() {
		SqlPara sqlPara = Db.use("boya").getSqlPara("FindLeafCategories");
		List<ByCategory> categories = ByCategory.dao.find(sqlPara);
		setAttr("categories", JSONUtil.toJsonStr(categories));
		render("/boya/storageForm.html");
	}

	public void editStorage() {
		Long id = getParaToLong("id");

		SqlPara sqlPara = Db.use("boya").getSqlPara("FindLeafCategories");
		List<ByCategory> categories = ByCategory.dao.find(sqlPara);

		ByStorage info = ByStorage.dao.findById(id);

		setAttr("categories", JSONUtil.toJsonStr(categories));
		setAttr("info", info);
		render("/boya/storageForm.html");
	}

	public void storageInfo() {
		String id = getPara("id");
		ByStorage info = ByStorage.dao.findById(id);
		if (info != null) {
			renderResult(info);
		} else {
			renderFailure(404, "not found");
		}
	}

	public void submitStorage() {
		Long id = getParaToLong("id");
		Long categoryId = getParaToLong("categoryId");
		String categoryString = getPara("categoryString");
		String name = getPara("name");
		BigDecimal weight = BigDecimal.valueOf(Double.valueOf(getPara("weight", "0")));
		String unit = getPara("unit");
		boolean isNew = id == null;
		ByStorage info = isNew ? new ByStorage() : ByStorage.dao.findById(id);
		if (!isNew && info == null) {
			renderFailure(404, "storage not found");
			return;
		}
		BigDecimal oldWeight = isNew ? new BigDecimal(0) : info.getWeight();
		if (isNew) {
			info.setSchoolId(getSchool().getId());
		}
		info.setCategoryId(categoryId);
		info.setCategoryString(categoryString);
		info.setName(name);
		info.setWeight(weight);
		info.setUnit(unit);
		boolean flag = isNew ? info.save() : info.update();
		if (flag) {
			if (isNew) {
				log("新增" + info.getName(), "+" + info.getWeight() + info.getUnit(), null);
			} else {
				log("更新" + info.getName(),
						weight.compareTo(oldWeight) >= 0 ? "+" + weight.subtract(oldWeight) + info.getUnit()
								: "-" + oldWeight.subtract(weight) + info.getUnit(),
						null);
			}
			renderSuccess();
		} else {
			renderFailure();
		}
	}

	public void updateStorage() {
		Long id = getParaToLong("id");
		BigDecimal weight = BigDecimal.valueOf(Double.valueOf(getPara("weight", "0")));
		if (id == null) {
			renderFailure(500, "id is null");
			return;
		}
		ByStorage info = ByStorage.dao.findById(id);
		if (info == null) {
			renderFailure(404, "storage is null");
			return;
		}
		BigDecimal oldWeight = info.getWeight();
		info.setWeight(weight);
		if (info.update()) {
			log("更新" + info.getName(),
					weight.compareTo(oldWeight) >= 0 ? "+" + weight.subtract(oldWeight) + info.getUnit()
							: "-" + oldWeight.subtract(weight) + info.getUnit(),
					null);
			renderSuccess();
		} else {
			renderFailure();
		}
	}

	public void delStorage() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderFailure(500, "id is null");
			return;
		}
		ByStorage info = ByStorage.dao.findById(id);
		if (info == null) {
			renderFailure(404, "storage not found");
			return;
		}
		// if (info.delete()) {
		// log("删除" + info.getName(), "-" + info.getWeight() + info.getUnit(),
		// null);
		// renderSuccess();
		// } else {
		// renderFailure();
		// }
		info.setFlag(1);
		if (info.update()) {
			log("删除" + info.getName(), "-" + info.getWeight() + info.getUnit(), null);
			renderSuccess();
		} else {
			renderFailure();
		}
	}

	public void genMenu() {
		render("/boya/genMenu.html");
	}

	public void addMenuItem() {
		SqlPara sqlPara = Db.use("boya").getSqlPara("FindStorage", Kv.by("schoolId", getSchool().getId()));
		List<ByStorage> storages = ByStorage.dao.find(sqlPara);
		setAttr("storages", JSONUtil.toJsonStr(storages));
		render("/boya/addMenuItem.html");
	}

	public void submitMeal() {
		Date date = DateUtil.parse(getPara("date"), "yyyy/MM/dd").toJdkDate();
		Integer type = getParaToInt("type");
		Integer count = getParaToInt("count");
		String content = getPara("content");
		if (StrKit.isBlank(content) || content.trim().equals("[]") || content.trim().equals("{}")) {
			renderFailure(500, "餐单列表不能为空");
			return;
		}

		// 生成消耗列表
		HashMap<Long, Integer> cost = new HashMap<>(); // <id, totalWeight>
		JSONArray list = JSONUtil.parseArray(content);
		for (int i = 0; i < list.size(); i++) {
			JSONObject obj = list.getJSONObject(i);
			JSONArray materials = obj.getJSONArray("list");
			for (int j = 0; j < materials.size(); j++) {
				JSONObject mtr = materials.getJSONObject(j);
				Long storageId = mtr.getLong("id");
				Integer weight = mtr.getInt("weight");
				if (cost.containsKey(storageId)) {
					cost.put(storageId, cost.get(storageId) + weight * count);
				} else {
					cost.put(storageId, weight * count);
				}
			}
		}
		// 检查库存余量并扣除库存
		Iterator<Map.Entry<Long, Integer>> entries = cost.entrySet().iterator();
		// while (entries.hasNext()) {
		// Map.Entry<Long, Integer> entry = entries.next();
		// ByStorage storage = ByStorage.dao.findById(entry.getKey());
		// if (storage.getWeight() < entry.getValue()) {
		// renderFailure(500, "库存不足！");
		// return;
		// }
		// }
		entries = cost.entrySet().iterator();
		while (entries.hasNext()) {
			Map.Entry<Long, Integer> entry = entries.next();
			ByStorage storage = ByStorage.dao.findById(entry.getKey());
			// storage.setWeight(storage.getWeight() - entry.getValue());
			// storage.update();

			log(storage.getName(), "-" + entry.getValue() + "g", null);
		}

		ByMeal info = new ByMeal();
		info.setDate(date);
		info.setType(type);
		info.setCount(count);
		info.setContent(content);
		info.setSchoolId(getSchool().getId().intValue());
		info.setAddTime();
		boolean flag = info.save();
		if (flag) {
			renderSuccess();
		} else {
			renderFailure();
		}
	}

	public void logs() {
		SqlPara sqlPara = Db.use("boya").getSqlPara("FindLogs", Kv.by("schoolId", getSchool().getId()));
		Page<ByLog> pages = ByLog.dao.paginate(getPage(), PAGE_SIZE, sqlPara);
		for (ByLog log : pages.getList()) {
			log.put("date", DateUtil.format(log.getAddTime(), "yyyy-MM-dd HH:mm:ss"));
		}
		setRainbow(pages);
		setAttr("list", JSONUtil.toJsonStr(pages.getList()));
		render("/boya/logs.html");
	}

	public void delLog() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderFailure(500, "id is null");
			return;
		}
		ByLog info = ByLog.dao.findById(id);
		if (info == null) {
			renderFailure(404, "log not found");
			return;
		}
		if (info.delete()) {
			renderSuccess();
		} else {
			renderFailure();
		}
	}

	public void nutrition() {
		SqlPara sqlPara = Db.use("boya").getSqlPara("FindMeals", Kv.by("schoolId", getSchool().getId()));
		List<ByMeal> list = ByMeal.dao.find(sqlPara);
		for (ByMeal meal : list) {
			meal.set("date", DateUtil.format(meal.getDate(), "yyyy-MM-dd"));
			meal.set("content", JSONUtil.parseArray(meal.getContent()));
		}
		setAttr("list", JSONUtil.toJsonStr(list));
		render("/boya/nutrition.html");
	}

	public void mealInfo() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderFailure(500, "id is null");
			return;
		}
		ByMeal info = ByMeal.dao.findById(id);
		if (info == null) {
			renderFailure(404, "meal not found");
			return;
		}

		sumNutrition(info, DateUtil.format(info.getDate(), "yyyy-MM-dd"), 1);
		render("/boya/nutritionInfo.html");
	}

	public void nutritionWithDate() {
		String startDate = getPara("startDate");
		String endDate = getPara("endDate");
		SqlPara sqlPara = Db.use("boya").getSqlPara("FindMealsWithDate",
				Kv.by("schoolId", getSchool().getId()).set("startDate", startDate).set("endDate", endDate));
		List<ByMeal> list = ByMeal.dao.find(sqlPara);
		ByMeal info = new ByMeal();

		JSONObject content = new JSONObject();
		content.put("name", "");

		JSONArray resultList = new JSONArray();
		for (ByMeal item : list) {
			JSONArray array = JSONUtil.parseArray(item.getContent());
			for (int i = 0; i < array.size(); i++) {
				JSONArray items = array.getJSONObject(i).getJSONArray("list");
				for (int j = 0; j < items.size(); j++) {
					JSONObject obj = items.getJSONObject(j); // 原料
					resultList.put(obj);
				}
			}
		}

		content.put("list", resultList);
		info.setContent(new JSONArray().put(content).toString());
		long days = DateUtil.between(DateUtil.parse(startDate), DateUtil.parse(endDate), DateUnit.DAY);
		sumNutrition(info, startDate + " ~ " + endDate, new Long(days).intValue() + 1);
		render("/boya/nutritionInfo.html");
	}

	private void sumNutrition(ByMeal info, String showDate, int days) {
		// 按原材料统计重量
		ArrayList<HashMap<String, Object>> list = new ArrayList<>();
		JSONArray array = JSONUtil.parseArray(info.getContent());
		for (int i = 0; i < array.size(); i++) {
			JSONArray items = array.getJSONObject(i).getJSONArray("list");
			for (int j = 0; j < items.size(); j++) {
				JSONObject obj = items.getJSONObject(j); // 原料
				int index = containsId(list, obj.getLong("id"));
				if (index >= 0) {
					list.get(index).put("weight",
							Integer.valueOf(list.get(index).get("weight").toString()) + obj.getInt("weight"));
				} else {
					HashMap<String, Object> map = new HashMap<>();
					map.put("id", obj.get("id"));
					map.put("name", obj.get("name"));
					map.put("categoryId", obj.get("categoryId"));
					SqlPara sqlPara = Db.use("boya").getSqlPara("FindSingleCategory", obj.get("categoryId"));
					ByCategory category = ByCategory.dao.findFirst(sqlPara);
					map.put("category", category.get("parentName") + " / " + category.get("name"));
					map.put("weight", obj.get("weight"));
					list.add(map);
				}
			}
		}

		// 营养统计
		HashMap<String, Float> result = new HashMap<>();
		result.put("heat", 0f);
		result.put("carbohydrateHeating", 0f); // 碳水化合物供热
		result.put("adiposeHeating", 0f); // 脂肪供热
		result.put("proteinHeating", 0f); // 蛋白质供热
		result.put("protein", 0f); // 蛋白质总量
		result.put("animalProtein", 0f); // 动物蛋白
		result.put("peaProtein", 0f); // 动豆蛋白
		result.put("calcium", 0f); // 钙
		result.put("vitamineA", 0f);
		result.put("vitamineB1", 0f);
		result.put("vitamineB2", 0f);
		result.put("vitamineC", 0f);
		result.put("vitamineE", 0f);
		result.put("vitaminePP", 0f);
		result.put("kalium", 0f); // 钾
		result.put("magnesium", 0f); // 镁
		result.put("ferrum", 0f); // 铁
		result.put("zinc", 0f); // 锌
		result.put("phosphorus", 0f); // 磷
		result.put("selenium", 0f); // 硒
		result.put("renieratene", 0f); // 胡萝卜素
		result.put("cholesterol", 0f); // 胆固醇
		result.put("fibre", 0f); // 纤维素
		for (HashMap<String, Object> item : list) {
			Long nutritionId = ByCategory.dao.findById(item.get("categoryId")).getNuturitionId();
			if (nutritionId == null) {
				LogKit.warn("缺少对应营养数据 categoryId = " + item.get("categoryId"));
				continue;
			}
			ByNutrition nutrition = ByNutrition.dao.findById(nutritionId);
			if (nutrition == null) {
				LogKit.warn("缺少对应营养数据 categoryId = " + item.get("categoryId"));
				continue;
			}
			result.put("heat",
					result.get("heat") + Integer.valueOf(item.get("weight").toString()) * nutrition.getHeat());
			result.put("carbohydrateHeating", result.get("carbohydrateHeating")
					+ Integer.valueOf(item.get("weight").toString()) * nutrition.getCarbohydrateHeating()); // 碳水化合物供热(kcal)
			result.put("adiposeHeating", result.get("adiposeHeating")
					+ Integer.valueOf(item.get("weight").toString()) * nutrition.getAdiposeHeating()); // 脂肪供热
			result.put("proteinHeating", result.get("proteinHeating")
					+ Integer.valueOf(item.get("weight").toString()) * nutrition.getProteinHeating()); // 蛋白质供热
			result.put("protein",
					result.get("protein") + Integer.valueOf(item.get("weight").toString()) * nutrition.getProtein()); // 蛋白质总量(g)
			result.put("animalProtein", result.get("animalProtein")
					+ Integer.valueOf(item.get("weight").toString()) * nutrition.getAnimalProtein()); // 动物蛋白(g)
			result.put("peaProtein", result.get("peaProtein")
					+ Integer.valueOf(item.get("weight").toString()) * nutrition.getPeaProtein()); // 动豆蛋白(g)
			result.put("calcium",
					result.get("calcium") + Integer.valueOf(item.get("weight").toString()) * nutrition.getCalcium()); // 钙(mg)
			result.put("vitamineA", result.get("vitamineA")
					+ Integer.valueOf(item.get("weight").toString()) * nutrition.getVitamineA()); // (ug)
			result.put("vitamineB1", result.get("vitamineB1")
					+ Integer.valueOf(item.get("weight").toString()) * nutrition.getVitamineB1()); // (mg)
			result.put("vitamineB2", result.get("vitamineB2")
					+ Integer.valueOf(item.get("weight").toString()) * nutrition.getVitamineB2()); // (mg)
			result.put("vitamineC", result.get("vitamineC")
					+ Integer.valueOf(item.get("weight").toString()) * nutrition.getVitamineC()); // (mg)
			result.put("vitamineE", result.get("vitamineE")
					+ Integer.valueOf(item.get("weight").toString()) * nutrition.getVitamineE()); // (mg)
			result.put("vitaminePP", result.get("vitaminePP")
					+ Integer.valueOf(item.get("weight").toString()) * nutrition.getVitaminePP()); // (mg)
			result.put("kalium",
					result.get("kalium") + Integer.valueOf(item.get("weight").toString()) * nutrition.getKalium()); // 钾(mg)
			result.put("magnesium", result.get("magnesium")
					+ Integer.valueOf(item.get("weight").toString()) * nutrition.getMagnesium()); // 镁(mg)
			result.put("ferrum",
					result.get("ferrum") + Integer.valueOf(item.get("weight").toString()) * nutrition.getFerrum()); // 铁(mg)
			result.put("zinc",
					result.get("zinc") + Integer.valueOf(item.get("weight").toString()) * nutrition.getZinc()); // 锌(mg)
			result.put("phosphorus", result.get("phosphorus")
					+ Integer.valueOf(item.get("weight").toString()) * nutrition.getPhosphorus()); // 磷(mg)
			result.put("selenium",
					result.get("selenium") + Integer.valueOf(item.get("weight").toString()) * nutrition.getSelenium()); // 硒(ug)
			result.put("renieratene", result.get("renieratene")
					+ Integer.valueOf(item.get("weight").toString()) * nutrition.getRenieratene()); // 胡萝卜素(ug)
			result.put("cholesterol", result.get("cholesterol")
					+ Integer.valueOf(item.get("weight").toString()) * nutrition.getCholesterol()); // 胆固醇(mg)
			result.put("fibre",
					result.get("fibre") + Integer.valueOf(item.get("weight").toString()) * nutrition.getFibre()); // 纤维素(g)
		}

		info.set("date", showDate);
		info.set("content", list);
		setAttr("info", JSONUtil.toJsonStr(info));
		setAttr("days", days);
		setAttr("nutrition", JSONUtil.toJsonStr(result));
	}

	/**
	 * 检查list是否存在目标id的object
	 * 
	 * @param list
	 * @param id
	 * @return 如果存在返回所在index，否则返回-1
	 */
	private int containsId(ArrayList<HashMap<String, Object>> list, Long id) {
		for (int i = 0; i < list.size(); i++) {
			HashMap<String, Object> item = list.get(i);
			if (id.equals(Long.valueOf((String) item.get("id")))) {
				return i;
			}
		}
		return -1;
	}

	public void delMeal() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderFailure(500, "id is null");
			return;
		}
		ByMeal info = ByMeal.dao.findById(id);
		if (info == null) {
			renderFailure(404, "meal not found");
			return;
		}
		if (info.delete()) {
			renderSuccess();
		} else {
			renderFailure();
		}
	}

	public void importList() {
		String startDate = getPara("startDate");
		String endDate = getPara("endDate");
		String supplier = getPara("supplier");
		Long storageId = getParaToLong("storageId");
		Kv kv = Kv.create();
		kv.set("schoolId", getSchool().getId());
		if (supplier != null) {
			kv.set("supplier", supplier);
			setAttr("supplier", supplier);
		}
		if (StrKit.notBlank(startDate)) {
			startDate = startDate + " 00:00:00";
			endDate = endDate + " 23:59:59";
			kv.set("startTime", startDate);
			kv.set("endTime", endDate);
			setAttr("startTime", startDate);
			setAttr("endTime", endDate);
		}
		if (storageId != null) {
			kv.set("storageId", storageId);
			setAttr("storageId", storageId);
		}

		Integer dl = getParaToInt("dl", 0);
		if (dl.equals(1)) {
			downloadImportList(kv);
			return;
		}
		SqlPara sqlPara = Db.use("boya").getSqlPara("FindImportList", kv);
		Page<ByImport> pages = ByImport.dao.paginate(getPage(), PAGE_SIZE, sqlPara);
		String[] proves = PropKit.get("BY_PROVES").split(";");
		for (ByImport item : pages.getList()) {
			String result = "";
			if (StrKit.notBlank(item.getProve())) {
				String[] proveIds = item.getProve().split(";");
				for (String id : proveIds) {
					result += proves[Integer.valueOf(id)] + "，";
				}
				item.setProve(result.substring(0, result.length() - 1));
			} else {
				item.setProve("无");
			}
		}
		SqlPara sqlPara2 = Db.use("boya").getSqlPara("FindStorage");
		List<ByStorage> storages = ByStorage.dao.find(sqlPara2);

		setRainbow(pages);
		setAttr("list", JsonKit.toJson(pages.getList()));
		setAttr("storages", JsonKit.toJson(storages));
		render("/boya/importList.html");
	}

	public void importInfo() {
		setReferer();
		Long id = getParaToLong("id");
		if (id != null) {
			ByImport info = ByImport.dao.findById(id);
			if (info == null) {
				renderFailure(404, "record not found");
				return;
			}
			setAttr("info", info);
		}

		SqlPara sqlPara = Db.use("boya").getSqlPara("FindStorage");
		List<ByStorage> storages = ByStorage.dao.find(sqlPara);
		setAttr("storages", JSONUtil.toJsonStr(storages));

		render("/boya/importForm.html");
	}

	public void delImport() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderFailure(500, "id is null");
			return;
		}
		ByImport info = ByImport.dao.findById(id);
		if (info == null) {
			renderFailure(404, "record not found");
			return;
		}
		ByStorage storage = ByStorage.dao.findById(info.getStorageId());
		if (storage != null && (storage.getFlag() == null || storage.getFlag() != 1)) {
			if (storage.getWeight().compareTo(info.getCount()) < 0) {
				renderFailure("库存不足，删除失败");
				return;
			}
			if (storage.getWeight().compareTo(info.getCount()) >= 0) {
				storage.setWeight(storage.getWeight().subtract(info.getCount()));
				if (storage.getWeight().intValue() == 0) {
					storage.delete();
				} else {
					storage.update();
				}
			}
		}
		if (info.delete()) {
			renderSuccess();
		} else {
			renderFailure();
		}
	}

	public void submitImport() {
		Long id = getParaToLong("id");
		String date = getPara("date");
		String name = getPara("name");
		String size = getPara("size");
		BigDecimal count = BigDecimal.valueOf(Double.valueOf(getPara("count", "0")));
		String no = getPara("no");
		String exp = getPara("exp");
		String supplier = getPara("supplier");
		String supplierTel = getPara("supplierTel");
		String prove = getPara("prove");
		String sender = getPara("sender");
		String acceptor = getPara("acceptor");
		String attachment = getPara("attachment");
		String storageId = getPara("storageId");
		String category = getPara("category");
		boolean isNew = id == null;
		ByImport info = isNew ? new ByImport() : ByImport.dao.findById(id);
		if (!isNew && info == null) {
			renderFailure(404, "record not found");
			return;
		}
		if (isNew) {
			info.setSchoolId(getSchool().getId().intValue());
			info.setAddTime();
		}

		// 增加库存
		ByStorage storage = null;
		if (storageId != null && isNew) {
			storage = ByStorage.dao.findById(storageId);
			if (storage != null) {
				storage.setWeight(storage.getWeight().add(count));
				storage.setProve(prove);
				storage.update();
				info.setStorageId(Long.valueOf(storageId));
			} else {
				storage = new ByStorage();
				storage.setName(storageId);
				storage.setWeight(count);
				storage.setUnit(size);
				storage.setCategoryString(category);
				storage.setProve(prove);
				storage.save();
				info.setStorageId(storage.getId());
			}
			log("新增" + storage.getName(), "+" + count + size, null);
		}

		if (StrKit.notBlank(date)) {
			info.setDate(DateUtil.parse(date, DateUtils.YYYYMMDD));
		} else {
			info.setDate(null);
		}
		info.setName(name);
		info.setSize(size);
		info.setCount(count);
		info.setNo(no);
		if (StrKit.notBlank(exp)) {
			info.setExp(DateUtil.parse(exp, DateUtils.YYYYMMDD));
		} else {
			info.setExp(null);
		}
		info.setSupplier(supplier);
		info.setSupplierTel(supplierTel);
		info.setProve(prove);
		info.setSender(sender);
		info.setAcceptor(acceptor);
		info.setAttachment(attachment);
		boolean flag = isNew ? info.save() : info.update();
		if (flag) {
			renderSuccess();
		} else {
			renderFailure();
		}
	}

	private void downloadImportList(Kv kv) {
		SqlPara sqlPara = Db.use("boya").getSqlPara("FindImportList", kv);
		List<ByImport> items = ByImport.dao.find(sqlPara);
		ArrayList<List<String>> arrayList = new ArrayList<>();

		List<String> title = CollUtil.newArrayList("采购日期", "产品名称", "产品规格", "进货数量", "产品批号", "保质期限", "供货商", "供货商联系方式",
				"营业执照", "食品经营许可证", "食品流通许可证", "检验证明", "购物凭证", "送货人", "验收人", "单位");
		arrayList.add(title);
		for (ByImport info : items) {
			String date = DateUtil.format(info.getDate(), DateUtils.YYYYMMDD);
			String storageName = info.get("storageName");
			String size = info.getSize();
			String count = info.getCount().toString();
			String no = info.getNo();
			String exp = DateUtil.format(info.getExp(), DateUtils.YYYYMMDD);
			String supplier = info.getSupplier();
			String supplierTel = info.getSupplierTel();
			String prove = "无";
			if (StrKit.notBlank(info.getProve())) {
				prove = "";
				String[] proves = PropKit.get("BY_PROVES").split(";");
				String[] proveIds = info.getProve().split(";");
				for (String id : proveIds) {
					prove += proves[Integer.valueOf(id)] + "，";
				}
				prove = prove.substring(0, prove.length() - 1);
			}
			String sender = info.getSender();
			String acceptor = info.getAcceptor();
			String schoolName = info.get("schoolName");

			String pem1 = prove.contains("营业执照") ? "√" : "";
			String pem2 = prove.contains("食品经营许可证") ? "√" : "";
			String pem3 = prove.contains("食品流通许可证") ? "√" : "";
			String pem4 = prove.contains("检验证明") ? "√" : "";
			String pem5 = prove.contains("购物凭证") ? "√" : "";
			List<String> row = CollUtil.newArrayList(date, storageName, size, count, no, exp, supplier, supplierTel,
					pem1, pem2, pem3, pem4, pem5, sender, acceptor, schoolName);
			arrayList.add(row);
		}
		String now = DateUtil.now();
		now = now.replace("-", "");
		now = now.replace(":", "");
		now = now.replace(" ", "");
		String name = "食品及原料进货索证台账登记本-" + now + ".xlsx";
		String path = PathUtils.getFile("by", "temp", "excel", name);
		ExcelWriter writer = ExcelUtil.getWriter(path);
		writer.write(arrayList);
		writer.close();
		File file = new File(path);
		renderFile(file);
	}

	public void exportList() {

		String startDate = getPara("startDate");
		String endDate = getPara("endDate");
		// Long schoolId = getParaToLong("schoolId");
		Long targetId = getParaToLong("targetId");
		Long storageId = getParaToLong("storageId");
		SqlPara sqlPara;
		Kv kv = Kv.create();
		if (!getSchool().getRole().equals(1)) {
			kv.set("schoolId", getSchool().getId());
		}
		if (targetId != null) {
			kv.set("targetId", targetId);
			setAttr("targetId", targetId);
		}
		if (StrKit.notBlank(startDate)) {
			startDate = startDate + " 00:00:00";
			endDate = endDate + " 23:59:59";
			kv.set("startTime", startDate);
			kv.set("endTime", endDate);
		}
		if (storageId != null) {
			kv.set("storageId", storageId);
			setAttr("storageId", storageId);
		}

		if (getParaToInt("dl", 0).equals(1)) {
			downloadExportList(kv);
			return;
		}
		sqlPara = Db.use("boya").getSqlPara("FindExportList", kv);
		Page<ByExport> pages = ByExport.dao.paginate(getPage(), PAGE_SIZE, sqlPara);
		String[] proves = PropKit.get("BY_PROVES").split(";");
		for (ByExport item : pages.getList()) {
			String result = "";
			if (StrKit.notBlank(item.getProve())) {
				String[] proveIds = item.getProve().split(";");
				for (String id : proveIds) {
					result += proves[Integer.valueOf(id)] + "，";
				}
				item.setProve(result.substring(0, result.length() - 1));
			} else {
				item.setProve("无");
			}
		}

		List<BySchool> schools = BySchool.dao.findAll();
		SqlPara sqlPara2 = Db.use("boya").getSqlPara("FindStorage");
		List<ByStorage> storages = ByStorage.dao.find(sqlPara2);

		setAttr("startTime", startDate);
		setAttr("endTime", endDate);
		setRainbow(pages);
		setAttr("list", JsonKit.toJson(pages.getList()));
		setAttr("schools", JsonKit.toJson(schools));
		setAttr("storages", JsonKit.toJson(storages));
		render("/boya/exportList.html");
	}

	public void exportInfo() {
		setReferer();
		Long id = getParaToLong("id");
		if (id != null) {
			ByExport info = ByExport.dao.findById(id);
			if (info == null) {
				renderFailure(404, "record not found");
				return;
			}
			setAttr("info", info);
		}
		SqlPara sqlPara = Db.use("boya").getSqlPara("FindNotAdminSchools");
		List<BySchool> schools = BySchool.dao.find(sqlPara);
		setAttr("schools", JSONUtil.toJsonStr(schools));
		SqlPara sqlPara2 = Db.use("boya").getSqlPara("FindStorage");
		List<ByStorage> storages = ByStorage.dao.find(sqlPara2);
		setAttr("storages", JSONUtil.toJsonStr(storages));
		render("/boya/exportForm.html");
	}

	public void exportBatch() {
		setReferer();
		SqlPara sqlPara = Db.use("boya").getSqlPara("FindNotAdminSchools");
		List<BySchool> schools = BySchool.dao.find(sqlPara);
		setAttr("schools", JSONUtil.toJsonStr(schools));
		SqlPara sqlPara2 = Db.use("boya").getSqlPara("FindStorage");
		List<ByStorage> storages = ByStorage.dao.find(sqlPara2);
		setAttr("storages", JSONUtil.toJsonStr(storages));
		render("/boya/exportBatch.html");
	}

	public void delExport() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderFailure(500, "id is null");
			return;
		}
		ByExport info = ByExport.dao.findById(id);
		if (info == null) {
			renderFailure(404, "record not found");
			return;
		}
		if (info.getImportId() != null) {
			ByImport imp = ByImport.dao.findById(info.getImportId());
			if (imp != null) {
				imp.delete();
			}
		}
		ByStorage storage = ByStorage.dao.findById(info.getStorageId());
		if (storage != null) {
			storage.setWeight(storage.getWeight().add(info.getCount()));
			storage.update();
		}
		if (info.delete()) {
			renderSuccess();
		} else {
			renderFailure();
		}
	}

	private BigDecimal getParaToDecimal(String name) {
		BigDecimal value = BigDecimal.valueOf(Double.valueOf(getPara(name, "0")));
		return value;
	}

	private BigDecimal getParaToDecimal(String name, int defaultValue) {
		BigDecimal value = BigDecimal.valueOf(Double.valueOf(getPara(name, "" + defaultValue)));
		return value;
	}

	public void submitExport() {
		Long id = getParaToLong("id");
		String target = getPara("target");
		String date = getPara("date");
		String name = getPara("name");
		BigDecimal count = getParaToDecimal("count");
		String attachment = getPara("attachment");
		String unit = getPara("unit");
		String price = getPara("price");
		String operator = getPara("operator");
		Long storageId = getParaToLong("storageId");
		Long targetId = getParaToLong("targetId");
		String acceptor = getPara("acceptor");
		String no = getPara("no");
		String exp = getPara("exp");

		boolean isNew = id == null;

		if (storageId == null) {
			renderFailure(500, "storage id is null");
			return;
		}
		ByStorage storage = ByStorage.dao.findById(storageId);
		if (count.compareTo(storage.getWeight()) > 0 && isNew) {
			renderFailure("库存不足");
			return;
		}

		ByExport info = isNew ? new ByExport() : ByExport.dao.findById(id);
		if (!isNew && info == null) {
			renderFailure(404, "record not found");
			return;
		}
		if (isNew) {
			info.setSchoolId(getSchool().getId().intValue());
			info.setAddTime();
			info.setProve(storage.getProve());
		}
		info.setTarget(target);
		if (StrKit.notBlank(date)) {
			info.setDate(DateUtil.parse(date, DateUtils.YYYYMMDD));
		} else {
			info.setDate(null);
		}
		info.setName(name);
		info.setCount(count);
		info.setAttachment(attachment);
		info.setUnit(unit);
		info.setPrice(BigDecimal.valueOf(Double.valueOf(price)));
		info.setOperator(operator);
		info.setStorageId(storageId);
		info.setTargetId(targetId);
		info.setAcceptor(acceptor);
		info.setNo(no);
		if (StrKit.notBlank(exp)) {
			info.setExp(DateUtil.parse(exp, DateUtils.YYYYMMDD));
		} else {
			info.setExp(null);
		}
		boolean flag = isNew ? info.save() : info.update();
		if (flag) {
			if (isNew) {
				// 自动生动配送经营点的进货索证台帐记录
				ByImport imp = new ByImport();
				imp.setSchoolId(info.getTargetId().intValue());
				imp.setStorageId(info.getStorageId());
				imp.setSize(info.getUnit());
				imp.setDate(info.getDate());
				imp.setCount(info.getCount());
				imp.setSupplier(getSchool().getName());
				imp.setSupplierTel(PropKit.get("BY_SUPPLIER_TEL", "13005550444"));
				imp.setSender(info.getOperator());
				imp.setAcceptor(info.getAcceptor());
				imp.save();

				info.setImportId(imp.getId());
				info.update();

				// 扣除库存
				if (storage != null) {
					storage.setWeight(storage.getWeight().subtract(info.getCount()));
					storage.update();
					log("配送" + storage.getName(), "-" + info.getCount() + info.getUnit(), null);
				}
				// 增加子账户库存
				// Kv kv = Kv.create();
				// kv.set("schoolId", targetId);
				// kv.set("storageId", storageId);
				// SqlPara sqlPara =
				// Db.use("boya").getSqlPara("FindStockBySchoolAndStorage",
				// kv);
				// ByStock stock = ByStock.dao.findFirst(sqlPara);
				// if (stock == null) {
				// stock = new ByStock();
				// stock.setName(name);
				// }
			}
			renderSuccess();
		} else {
			renderFailure();
		}
	}

	public void submitExportBatch() {
		String date = getPara("date");
		Long targetId = getParaToLong("targetId");
		String operator = getPara("operator");
		String acceptor = getPara("acceptor");
		String attachment = getPara("attachment");
		String storagesJson = getPara("storagesJson");
		
		JSONArray storages = JSONUtil.parseArray(storagesJson);
		boolean flag = Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
				for (int i = 0; i < storages.size(); i ++) {
					JSONObject storageObj = storages.getJSONObject(i);
					Long storageId = storageObj.getLong("storageId");
					String unit = storageObj.getStr("unit");
					String exp = storageObj.getStr("exp");
					String no = storageObj.getStr("no");
					BigDecimal count = BigDecimal.valueOf(Double.valueOf(storageObj.getStr("count", "0")));
					BigDecimal price = BigDecimal.valueOf(Double.valueOf(storageObj.getStr("price", "0")));

					if (storageId == null) {
						renderFailure(500, "storage id is null");
						return false;
					}
					ByStorage storage = ByStorage.dao.findById(storageId);
					if (storage == null) {
						renderFailure(404, "库存未找到，id无效");
						return false;
					}
					if (count.compareTo(storage.getWeight()) > 0) {
						renderFailure("库存不足");
						return false;
					}

					ByExport info = new ByExport();
					info.setSchoolId(getSchool().getId().intValue());
					info.setAddTime();
					info.setProve(storage.getProve());
					if (StrKit.notBlank(date)) {
						info.setDate(DateUtil.parse(date, DateUtils.YYYYMMDD));
					} else {
						info.setDate(null);
					}
					info.setCount(count);
					info.setAttachment(attachment);
					info.setUnit(unit);
					info.setPrice(price);
					info.setOperator(operator);
					info.setStorageId(storageId);
					info.setTargetId(targetId);
					info.setAcceptor(acceptor);
					info.setNo(no);
					if (StrKit.notBlank(exp)) {
						info.setExp(DateUtil.parse(exp, DateUtils.YYYYMMDD));
					} else {
						info.setExp(null);
					}
					info.save();
					
					// 自动生动配送经营点的进货索证台帐记录
					ByImport imp = new ByImport();
					imp.setSchoolId(info.getTargetId().intValue());
					imp.setStorageId(info.getStorageId());
					imp.setSize(info.getUnit());
					imp.setDate(info.getDate());
					imp.setCount(info.getCount());
					imp.setSupplier(getSchool().getName());
					imp.setSupplierTel(PropKit.get("BY_SUPPLIER_TEL", "13005550444"));
					imp.setSender(info.getOperator());
					imp.setAcceptor(info.getAcceptor());
					imp.save();

					info.setImportId(imp.getId());
					info.update();

					// 扣除库存
					storage.setWeight(storage.getWeight().subtract(info.getCount()));
					storage.update();
					log("配送" + storage.getName(), "-" + info.getCount() + info.getUnit(), null);
				}
				return true;
			}
		});
		if (flag) {
			renderSuccess();
		} else {
			renderFailure();
		}
	}

	private void downloadExportList(Kv kv) {
		SqlPara sqlPara;
		// Kv kv = Kv.create();
		// if (!getSchool().getRole().equals(1)) {
		// kv.set("schoolId", getSchool().getId());
		// }
		sqlPara = Db.use("boya").getSqlPara("FindExportList", kv);
		List<ByExport> items = ByExport.dao.find(sqlPara);
		ArrayList<List<String>> arrayList = new ArrayList<>();
		List<String> title = CollUtil.newArrayList("配送日期", "配送经营点", "配送产品", "配送单位	", "数量", "单价", "金额", "营业执照",
				"食品经营许可证", "食品流通许可证", "检验证明", "购物凭证", "经手人", /*"验收人", */"验收签名");
		arrayList.add(title);
		for (ByExport info : items) {
			String date = DateUtil.format(info.getDate(), DateUtils.YYYYMMDD);
			String targetName = info.get("targetName");
			String storageName = info.get("storageName");
			String unit = info.getUnit();
			String count = info.getCount().toString();
			String price = info.getPrice().toString();
			String total = String.valueOf(info.getCount().multiply(info.getPrice()));
			String prove = "无";
			if (StrKit.notBlank(info.getProve())) {
				prove = "";
				String[] proves = PropKit.get("BY_PROVES").split(";");
				String[] proveIds = info.getProve().split(";");
				for (String id : proveIds) {
					prove += proves[Integer.valueOf(id)] + "，";
				}
				prove = prove.substring(0, prove.length() - 1);
			}
			String operator = info.getOperator();
//			String acceptor = info.getAcceptor();

			String pem1 = prove.contains("营业执照") ? "√" : "";
			String pem2 = prove.contains("食品经营许可证") ? "√" : "";
			String pem3 = prove.contains("食品流通许可证") ? "√" : "";
			String pem4 = prove.contains("检验证明") ? "√" : "";
			String pem5 = prove.contains("购物凭证") ? "√" : "";

			List<String> row = CollUtil.newArrayList(date, targetName, storageName, unit, count, price, total, pem1,
					pem2, pem3, pem4, pem5, operator, /*acceptor, */"");
			arrayList.add(row);
		}
		String now = DateUtil.now();
		now = now.replace("-", "");
		now = now.replace(":", "");
		now = now.replace(" ", "");
		String name = "食品及原料配送记录-" + now + ".xlsx";
		String path = PathUtils.getFile("by", "temp", "excel", name);
		ExcelWriter writer = ExcelUtil.getWriter(path);
		writer.write(arrayList);
		writer.close();
		File file = new File(path);
		renderFile(file);
	}

	public void stock() {
		Long schoolId = getParaToLong("schoolId");
		String startDate = getPara("startDate");
		String endDate = getPara("endDate");
		Long storageId = getParaToLong("storageId");
		String name = getPara("name");
		String type = getPara("type");
		String size = getPara("size");
		Kv kv = Kv.create();
		if (getSchool().getRole().equals(1)) {
			if (schoolId != null) {
				kv.set("schoolId", schoolId);
				setAttr("schoolId", schoolId);
			}
		} else {
			kv.set("schoolId", getSchool().getId());
		}
		if (StrKit.notBlank(startDate)) {
			startDate = startDate + " 00:00:00";
			endDate = endDate + " 23:59:59";
			kv.set("startTime", startDate);
			kv.set("endTime", endDate);
			setAttr("startTime", startDate);
			setAttr("endTime", endDate);
		}
		if (storageId != null) {
			kv.set("storageId", storageId);
			setAttr("storageId", storageId);
		}
		if (StrKit.notBlank(name)) {
			kv.set("name", name);
			setAttr("name", name);
		}
		if (StrKit.notBlank(type)) {
			kv.set("type", type);
			setAttr("type", type);
		}
		if (StrKit.notBlank(size)) {
			kv.set("size", size);
			setAttr("searchSize", size);
		}
		SqlPara sqlPara = Db.use("boya").getSqlPara("FindStock", kv);
		Page<ByStock> pages = ByStock.dao.paginate(getPage(), PAGE_SIZE, sqlPara);
		List<BySchool> schools = BySchool.dao.findAll();
		SqlPara sqlPara2 = Db.use("boya").getSqlPara("FindStorage");
		List<ByStorage> storages = ByStorage.dao.find(sqlPara2);
		setRainbow(pages);
		setAttr("list", pages.getList());
		setAttr("schools", JSONUtil.toJsonStr(schools));
		setAttr("storages", JSONUtil.toJsonStr(storages));
		render("/boya/stock.html");
	}

	public void stockInfo() {
		Long id = getParaToLong("id");
		if (id != null) {
			ByStock info = ByStock.dao.findById(id);
			if (info == null) {
				renderFailure(404, "stock not found");
				return;
			}
			setAttr("info", info);
		}
		// List<BySchool> schools = BySchool.dao.findAll();
		// setAttr("schools", JSONUtil.toJsonStr(schools));
		render("/boya/stockForm.html");
	}

	public void delStock() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderFailure(500, "id is null");
			return;
		}
		ByStock info = ByStock.dao.findById(id);
		if (info == null) {
			renderFailure(404, "stock not found");
			return;
		}

		// 非管理员删除增加管理员库存
		if (!getSchool().getRole().equals(1)) {
			ByStock parentStock = ByStock.dao.findById(info.getStockId());
			parentStock.setCount(parentStock.getCount().add(info.getCount()));
			parentStock.update();
			ByStockLog log = new ByStockLog();
			log.setStockId(parentStock.getId());
			log.setCount(info.getCount());
			log.setAfter(parentStock.getCount());
			log.setSchoolId(parentStock.getSchoolId());
			log.setAddTime();
			log.save();
		}

		if (info.delete()) {
			// ByStockLog log = new ByStockLog();
			// log.setStockId(info.getId()); // stockId is not found
			// log.setCount(-info.getCount());
			// log.setSchoolId(info.getSchoolId());
			// log.setAddTime();
			// log.save();
			renderSuccess();
		} else {
			renderFailure();
		}
	}

	private BigDecimal getZero() {
		return new BigDecimal("0");
	}

	public void submitStock() {
		Long id = getParaToLong("id");
		String name = getPara("name");
		BigDecimal count = getParaToDecimal("count");
		String category = getPara("category");
		String type = getPara("type");
		String size = getPara("size");
		String remark = getPara("remark");
		Long storageId = getParaToLong("storageId", 0L);
		// Long schoolId = getParaToLong("schoolId");
		boolean isNew = id == null;
		ByStock info = isNew ? new ByStock() : ByStock.dao.findById(id);
		if (!isNew && info == null) {
			renderFailure(404, "stock not found");
			return;
		}
		BigDecimal oldCount = isNew ? getZero() : info.getCount();
		if (isNew) {
			info.setSchoolId(getSchool().getId());
			info.setAddTime();
		}
		// info.setSchoolId(schoolId);
		info.setName(name);
		info.setCount(count);
		info.setCategory(category);
		info.setType(type);
		info.setSize(size);
		info.setRemark(remark);
		info.setStorageId(storageId);
		boolean flag = isNew ? info.save() : info.update();
		if (flag) {
			ByStockLog log = new ByStockLog();
			log.setStockId(info.getId());
			log.setCount(info.getCount().subtract(oldCount));
			log.setAfter(info.getCount());
			log.setSchoolId(info.getSchoolId());
			log.setAddTime();
			log.save();
			renderSuccess();
		} else {
			renderFailure();
		}
	}

	public void updateStock() {
		Long id = getParaToLong("id");
		BigDecimal count = getParaToDecimal("count");
		Integer type = getParaToInt("type");
		Long schoolId = getParaToLong("schoolId");
		if (id == null) {
			renderFailure(500, "id is null");
			return;
		}
		ByStock info = ByStock.dao.findById(id);
		if (info == null) {
			renderFailure(404, "stock not found");
			return;
		}
		BigDecimal oldCount = info.getCount();
		if (type.equals(0)) { // 增加
			info.setCount(info.getCount().add(count));

		} else { // 使用
			if (count.compareTo(info.getCount()) > 0) {
				renderFailure(500, "库存不足");
				return;
			}
			if (getSchool().getRole().equals(1)) { // 管理员使用
				Kv kv = Kv.create();
				kv.set("schoolId", schoolId);
				kv.set("stockId", id);
				SqlPara sqlPara = Db.use("boya").getSqlPara("FindStockBySchoolAndStock", kv);
				ByStock stock = ByStock.dao.findFirst(sqlPara);
				if (stock == null) { // 新增子账户库存
					stock = new ByStock();
					stock.setName(info.getName());
					stock.setCount(count);
					stock.setAddTime();
					stock.setSchoolId(schoolId);
					stock.setCategory(info.getCategory());
					stock.setType(info.getType());
					stock.setSize(info.getSize());
					stock.setRemark(info.getRemark());
					stock.setStockId(info.getId());
					stock.save();
				} else { // 更新子账户库存
					stock.setCount(stock.getCount().add(count));
					stock.update();
				}
				ByStockLog log = new ByStockLog();
				log.setStockId(stock.getId());
				log.setCount(count);
				log.setAfter(stock.getCount());
				log.setSchoolId(stock.getSchoolId());
				log.setAddTime();
				log.save();
			}
			info.setCount(info.getCount().subtract(count));
		}
		boolean flag = info.update();
		if (flag) {
			ByStockLog log = new ByStockLog();
			log.setStockId(info.getId());
			log.setCount(info.getCount().subtract(oldCount));
			log.setAfter(info.getCount());
			log.setSchoolId(info.getSchoolId());
			log.setAddTime();
			log.save();
			renderSuccess();
		} else {
			renderFailure();
		}
	}

	public void useStockForm() {
		Long id = getParaToLong("id");
		Integer type = getParaToInt("type");
		if (id == null) {
			renderFailure("id is null");
			return;
		}
		ByStock info = ByStock.dao.findById(id);
		if (info == null) {
			renderFailure(404, "stock not found");
			return;
		}
		setAttr("info", info);

		SqlPara sqlPara = Db.use("boya").getSqlPara("FindNotAdminSchools");
		List<BySchool> schools = BySchool.dao.find(sqlPara);
		setAttr("schools", JSONUtil.toJsonStr(schools));

		setAttr("type", type);
		render("/boya/stockUseForm.html");
	}

	public void stockLog() {
		Long schoolId = getParaToLong("schoolId");
		String startDate = getPara("startDate");
		String endDate = getPara("endDate");
		String name = getPara("name");
		String type = getPara("type");
		String size = getPara("size");
		Integer isUse = getParaToInt("isUse");
		Kv kv = Kv.create();
		if (!getSchool().getRole().equals(1)) {
			kv.set("schoolId", getSchool().getId());
		} else if (schoolId != null) {
			kv.set("schoolId", schoolId);
			setAttr("schoolId", schoolId);
		}
		if (StrKit.notBlank(startDate)) {
			startDate = startDate + " 00:00:00";
			endDate = endDate + " 23:59:59";
			kv.set("startTime", startDate);
			kv.set("endTime", endDate);
			setAttr("startTime", startDate);
			setAttr("endTime", endDate);
		}
		if (isUse != null) { // 1出库 2入库
			kv.set("isUse", isUse);
			setAttr("isUse", isUse);
		}
		if (StrKit.notBlank(name)) {
			kv.set("name", name);
			setAttr("name", name);
		}
		if (StrKit.notBlank(type)) {
			kv.set("type", type);
			setAttr("type", type);
		}
		if (StrKit.notBlank(size)) {
			kv.set("size", size);
			setAttr("stockSize", size);
		}
		SqlPara sqlPara = Db.use("boya").getSqlPara("FindStockLog", kv);
		Page<ByStockLog> pages = ByStockLog.dao.paginate(getPage(), PAGE_SIZE, sqlPara);
		for (ByStockLog log : pages.getList()) {
			log.put("date", DateUtil.format(log.getAddTime(), "yyyy-MM-dd HH:mm:ss"));
		}
		List<BySchool> schools = BySchool.dao.findAll();
		
		setRainbow(pages);
		setAttr("list", JSONUtil.toJsonStr(pages.getList()));
		setAttr("schools", JSONUtil.toJsonStr(schools));
		render("/boya/stockLog.html");
	}

	public void delStockLog() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderFailure(500, "id is null");
			return;
		}
		ByStockLog info = ByStockLog.dao.findById(id);
		if (info == null) {
			renderFailure(404, "log not found");
			return;
		}
		if (info.delete()) {
			renderSuccess();
		} else {
			renderFailure();
		}
	}

	public void reportList() {
		SqlPara sqlPara;
		// if (getSchool().getRole().equals(1)) {
		sqlPara = Db.use("boya").getSqlPara("FindReport");
		// } else {
		// sqlPara = Db.use("boya").getSqlPara("FindReport", Kv.by("schoolId",
		// getSchool().getId()));
		// }
		Page<ByReport> pages = ByReport.dao.paginate(getPage(), PAGE_SIZE, sqlPara);
		setRainbow(pages);
		setAttr("list", JSONUtil.toJsonStr(pages.getList()));
		render("/boya/report.html");
	}

	public void reportInfo() {
		setReferer();
		Long id = getParaToLong("id");
		if (id != null) {
			ByReport info = ByReport.dao.findById(id);
			if (info == null) {
				renderFailure(404, "report not found");
				return;
			}
			setAttr("info", info);
		}
		render("/boya/reportForm.html");
	}

	public void delReport() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderFailure(500, "id is null");
			return;
		}
		ByReport info = ByReport.dao.findById(id);
		if (info == null) {
			renderFailure(404, "report not found");
			return;
		}
		if (info.delete()) {
			renderSuccess();
		} else {
			renderFailure();
		}
	}

	public void submitReport() {
		Long id = getParaToLong("id");
		String date = getPara("date");
		String operator = getPara("operator");
		String name = getPara("name");
		Integer result = getParaToInt("result");
		String attachment = getPara("attachment");
		boolean isNew = id == null;
		ByReport info = isNew ? new ByReport() : ByReport.dao.findById(id);
		if (!isNew && info == null) {
			renderFailure(404, "report not found");
			return;
		}
		if (isNew) {
			info.setSchoolId(getSchool().getId().intValue());
			info.setAddTime();
		}
		info.setDate(date);
		info.setOperator(operator);
		info.setName(name);
		info.setResult(result);
		info.setAttachment(attachment);
		boolean flag = isNew ? info.save() : info.update();
		if (flag) {
			renderSuccess();
		} else {
			renderFailure();
		}
	}
	
	public void certList() {
		String title = getPara("title");
		Kv kv = Kv.create();
		if (StrKit.notBlank(title)) {
			kv.set("title", title);
			setAttr("title", title);
		}
		SqlPara sqlPara = Db.use("boya").getSqlPara("FindCert", kv);
		Page<ByCertification> pages = ByCertification.dao.paginate(getPage(), PAGE_SIZE, sqlPara);
		setRainbow(pages);
		setAttr("list", JsonKit.toJson(pages.getList()));
		render("/boya/cert.html");
	}
	
	public void certInfo() {
		setReferer();
		Long id = getParaToLong("id");
		if (id != null) {
			ByCertification info = ByCertification.dao.findById(id);
			if (info == null) {
				renderFailure(404, "not found");
				return;
			}
			setAttr("info", info);
		}
		render("/boya/certForm.html");
	}
	
	public void submitCert() {
		Long id = getParaToLong("id");
		String title = getPara("title");
		String images = getPara("images");
		boolean isNew = id == null;
		ByCertification info = isNew ? new ByCertification() : ByCertification.dao.findById(id);
		if (!isNew && info == null) {
			renderFailure(404, "certification not found");
			return;
		}
		info.setTitle(title);
		info.setImages(images);
		info.setAddTime();
		renderFlag(isNew ? info.save() : info.update());
	}
	
	public void delCert() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderFailure(500, "id is null");
			return;
		}
		ByCertification info = ByCertification.dao.findById(id);
		if (info == null) {
			renderFailure(404, "cert not found");
			return;
		}
		if (info.delete()) {
			renderSuccess();
		} else {
			renderFailure();
		}
	}
	
	public void certView() {
		setReferer();
		Long id = getParaToLong("id");
		if (id != null) {
			ByCertification info = ByCertification.dao.findById(id);
			if (info == null) {
				renderFailure(404, "not found");
				return;
			}
			setAttr("info", info);
		}
		render("/boya/certView.html");
	}

	/**
	 * test
	 */
	public void files() {
		String name = getPara("name");
		if (StrKit.isBlank(name)) {
			renderFailure();
			return;
		}
		File file = new File(PathKit.getWebRootPath() + File.separatorChar + "upload" + File.separatorChar + name);
		if (!file.exists()) {
			renderFailure(404, "not found");
			return;
		}
		renderFile(file);
	}

}
